package com.diyunapp.xilinapp.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.orhanobut.logger.Logger;


/**
 * Created by apple on 16/4/12.
 */
public class CodeCountDown implements Runnable{

    private static volatile CodeCountDown singleton = null;
    private CodeCountDown(){};
    private Context context;
    private TextView target;

    @Override
    public void run() {
        for(int i = 60 ;i >= 0;i --){
            handler.sendEmptyMessage(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Logger.e(e.getMessage());
            }
        }
    }

    public static CodeCountDown with(Context ctx){

        if(null == singleton){
            synchronized (CountDown.class){

                if(null == singleton ){
                    singleton = new CodeCountDown();
                }
            }
        }

        return singleton;
    }

    public void start(){

        new Thread(this).start();
    }

    public void into(TextView t){
        this.target = t;
        target.setClickable(false);
        start();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(0 == msg.what){
                target.setText("重新发送验证码");
                target.setClickable(true);
            }else{
                target.setText(msg.what+"秒");
            }
        }
    };
}